package com.gin.no_gay_alliance.viewmodel;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.no_gay_alliance.database.entity.IpLocationHistory;

import java.util.ArrayList;
import java.util.List;

/**
 * IP属地分组
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/12/26 15:11
 **/
public class IpLocationHistoryGroup {
    /**
     * 起始时间
     */
    public long start;
    /**
     * 结束时间
     */
    public long end;
    /**
     * IP属地
     */
    public String ipLocation;
    /**
     * 本分组包含的时间戳
     */
    public List<Long> timestamps;

    public IpLocationHistoryGroup(long time, String ipLocation) {
        this.start = time;
        this.end = time;
        this.ipLocation = ipLocation;
        this.timestamps = new ArrayList<>();
        this.timestamps.add(time);
    }

    public IpLocationHistoryGroup() {
    }

    /**
     * 将一份IP属地历史分组
     *
     * @param ipLocationHistories IP属地历史
     * @return IP属地分组
     */
    public static List<IpLocationHistoryGroup> group(List<IpLocationHistory> ipLocationHistories) {
        ArrayList<IpLocationHistoryGroup> res = new ArrayList<>();
        if (ObjectUtils.isEmpty(ipLocationHistories)) {
            return res;
        }
        for (IpLocationHistory history : ipLocationHistories) {
            // 如果为第一个，直接添加
            if (res.isEmpty()) {
                add(res, history);
            } else {
                // 取最后一个分组进行比较
                IpLocationHistoryGroup last = res.get(res.size() - 1);
                // 如果最后一个分组的属地与当前历史一致，则更新分组的时间；否则新增一个分组
                if (last.ipLocation.equals(history.ipLocation)) {
                    last.end = history.timestamp;
                    last.timestamps.add(history.timestamp);
                } else {
                    add(res, history);
                }
            }
        }

        return res;
    }

    /**
     * 添加一个新分组到分组列表
     *
     * @param res     分组列表
     * @param history 历史
     */
    private static void add(ArrayList<IpLocationHistoryGroup> res, IpLocationHistory history) {
        res.add(new IpLocationHistoryGroup(history.timestamp, history.ipLocation));
    }

}
